package com.sa07.ui.model;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import org.apache.log4j.Logger;

import com.sa07.ui.bean.TestBean;

/**
 * 默认格数据模板
 * 
 * @author Long.shangbo
 *
 * 2014-2-15 上午4:31:52
 */
public abstract class DefaultTestTableModel extends AbstractTableModel {
	
	private static final Logger logger = Logger.getLogger(DefaultTestTableModel.class);

	private static final long serialVersionUID = -1434885315981067670L;
	
	private List<TestBean> testDatas = new ArrayList<TestBean>();
	
	public static final String TEST_ID = "编号";
	public static final String TEST_RESULT = "测试结果";
	public static final String TEST_ITEM_NAME = "测试项名称";
	public static final String TEST_PRODUCT_CODE = "产品条形码";
	public static final String TEST_TIME = "测试时间";
	
	@Override
	public Object getValueAt(int row, int column) {
		TestBean testData = testDatas.get(row);
		
		if(testData != null){
			String field = getFields()[column];
			Class<? extends TestBean> clazz = testData.getClass();
			
			try {
				Field currField = clazz.getDeclaredField(field);
				currField.setAccessible(true);
				return currField.get(testData);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e);
			}
		}
		
		return "";
	}

	/**
	 * 设置数据
	 */
	public void setDatas(List<TestBean> testDatas){
		if(testDatas != null){
			this.testDatas = testDatas;
			fireTableDataChanged();
		}
	}
	
	/**
	 * 放入数据
	 * @param testData
	 */
	public void putData(TestBean testData){
		if(testData != null){
			testDatas.add(testData);
			fireTableDataChanged();
		}
	}
	
	/**
	 * 刷新
	 */
	public void refresh(){
		fireTableDataChanged();
	}
	
	/**
	 * 清空数据
	 */
	public void clear(){
		this.testDatas.clear();
		fireTableDataChanged();
	}
	
	/**
	 * 获得数据
	 * @return
	 */
	public List<TestBean> getData(){
		return this.testDatas;
	}
	
	@Override
	public Class<?> getColumnClass(int columnIndex) {
		return getFields()[columnIndex].getClass();
	}
	
	@Override
	public String getColumnName(int column) {
		return getHeaders()[column];
	}
	
	@Override
	public int getRowCount() {
		return testDatas.size();
	}
	
	@Override
	public int getColumnCount() {
		return getHeaders().length;
	}
	
	/**
	 * 获得标题
	 * @return
	 */
	protected abstract String[] getHeaders();
	
	/**
	 * 获得字段，必须与标题对应
	 * @return
	 */
	protected abstract String[] getFields();
}
